import pandas as pd
import requests
from bs4 import BeautifulSoup


def get_enterprise_address(enterprise_name):
    """
    根据企业名称从百度搜索获取地址
    """
    url = f"https://www.baidu.com/s?wd={enterprise_name} 地址"
    headers = {
        "User - Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
    }
    try:
        response = requests.get(url, headers=headers)
        response.raise_for_status()
        soup = BeautifulSoup(response.text, 'html.parser')
        address_element = soup.find('div', class_='c-abstract')
        if address_element:
            address = address_element.text.strip()
            print(f"企业 {enterprise_name} 的地址为: {address}")
            return address
        print(f"未找到企业 {enterprise_name} 的地址")
        return ''
    except requests.RequestException as e:
        print(f"请求出错: {e}")
        return ''


def update_excel_address(file_path):
    """
    读取 Excel 文件，查询第一列企业名称的地址并写入第二列
    """
    try:
        df = pd.read_excel(file_path)
        for index, row in df.iterrows():
            enterprise_name = row.iloc[0]
            address = get_enterprise_address(enterprise_name)
            df.at[index, 1] = address
        df.to_excel(file_path, index=False)
        print("数据更新成功。")
    except FileNotFoundError:
        print(f"未找到文件: {file_path}，请检查文件路径是否正确。")
    except Exception as e:
        print(f"处理文件时出现错误: {e}")


if __name__ == "__main__":
    file_path = 'test.xlsx'
    update_excel_address(file_path)
